from django.shortcuts import render

# Create your views here.

"""
SCL-90心理评估API视图

提供问卷提交、结果查询、短链接生成等API接口
"""
import asyncio
from datetime import datetime
from django.http import HttpResponseRedirect
from django.conf import settings
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.request import Request
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

from .models import (
    AssessmentData, AssessmentResult, 
    generate_test_id, get_risk_level
)
from .serializers import (
    AssessmentSubmissionSerializer, AssessmentResultSerializer,
    SubmissionResponseSerializer, ShortUrlRequestSerializer,
    ShortUrlResponseSerializer, ErrorResponseSerializer
)
from .storage import storage
from .scl90_algorithm import SCL90Algorithm
from .ai_service import ai_service


@swagger_auto_schema(
    method='post',
    request_body=AssessmentSubmissionSerializer,
    responses={
        200: SubmissionResponseSerializer,
        400: ErrorResponseSerializer,
        500: ErrorResponseSerializer
    },
    operation_description="提交SCL-90心理健康问卷数据并获取分析结果",
    operation_summary="提交心理评估问卷"
)
@api_view(['POST'])
def submit_assessment(request: Request) -> Response:
    """
    提交心理评估问卷
    
    接收用户的基本信息和SCL-90问卷答案，进行分析并返回结果
    """
    try:
        # 记录请求数据用于调试
        print(f"收到提交请求，数据: {request.data}")
        
        # 数据验证
        serializer = AssessmentSubmissionSerializer(data=request.data)
        if not serializer.is_valid():
            print(f"数据验证失败: {serializer.errors}")
            return Response({
                'success': False,
                'error': 'validation_error',
                'message': '数据验证失败',
                'details': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 创建评估数据对象
        assessment_data = serializer.save()
        
        # 验证评估数据
        if not assessment_data.validate():
            return Response({
                'success': False,
                'error': 'invalid_data',
                'message': '评估数据无效'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 存储评估数据
        if not storage.store_assessment_data(assessment_data):
            return Response({
                'success': False,
                'error': 'storage_error',
                'message': '数据存储失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        # 计算总分和平均分
        total_score = SCL90Algorithm.calculate_total_score(assessment_data.scl_answers)
        average_score = SCL90Algorithm.calculate_average_score(total_score)
        risk_level = get_risk_level(total_score)
        
        # 生成基础分析报告
        basic_report = SCL90Algorithm.generate_basic_analysis(
            total_score, average_score, assessment_data.basic_info
        )
        
        # 生成增强版基础报告作为备选
        enhanced_basic_report = SCL90Algorithm.generate_enhanced_basic_analysis(
            total_score, average_score, assessment_data.basic_info
        )
        
        # AI增强分析（如果配置了AI服务）- 带超时控制
        enhanced_report = enhanced_basic_report  # 默认使用增强版基础报告
        
        if ai_service.api_key:
            try:
                print(f"AI服务已配置，开始AI增强分析...")
                
                # 使用线程池执行AI调用，避免阻塞主线程
                import concurrent.futures
                
                def ai_enhance_sync():
                    return asyncio.run(ai_service.enhance_analysis_report(
                        total_score, average_score, assessment_data.basic_info, basic_report
                    ))
                
                # 使用线程池执行，设置超时时间
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    future = executor.submit(ai_enhance_sync)
                    try:
                        # 设置45秒超时
                        ai_result = future.result(timeout=45)
                        
                        if ai_result and len(ai_result.strip()) > len(enhanced_basic_report):
                            enhanced_report = ai_result
                            print(f"AI分析成功，报告长度: {len(enhanced_report)}")
                        else:
                            print("AI分析返回空或短内容，使用增强版基础报告")
                            
                    except concurrent.futures.TimeoutError:
                        print("AI服务总体超时（45秒），使用增强版基础报告")
                        future.cancel()  # 尝试取消任务
                        
            except Exception as e:
                print(f"AI增强分析执行失败，使用增强版基础报告: {e}")
        else:
            print("AI服务未配置，使用增强版基础报告")
        
        # 生成建议
        recommendations = SCL90Algorithm.generate_recommendations(
            total_score, assessment_data.basic_info
        )
        
        # 生成短链接
        short_url = f"https://你的域名/r/{assessment_data.test_id}"
        
        # 创建评估结果
        assessment_result = AssessmentResult(
            test_id=assessment_data.test_id,
            total_score=total_score,
            average_score=average_score,
            analysis_report=enhanced_report,
            recommendations=recommendations,
            risk_level=risk_level,
            short_url=short_url,
            created_at=datetime.now(),
            basic_info=assessment_data.basic_info
        )
        
        # 存储评估结果
        if not storage.store_assessment_result(assessment_result):
            return Response({
                'success': False,
                'error': 'storage_error',
                'message': '结果存储失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        # 返回成功响应
        return Response({
            'success': True,
            'test_id': assessment_data.test_id,
            'analysis': enhanced_report,
            'short_url': short_url
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        print(f"提交评估时发生错误: {e}")
        return Response({
            'success': False,
            'error': 'server_error',
            'message': '服务器内部错误'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@swagger_auto_schema(
    method='get',
    responses={
        200: AssessmentResultSerializer,
        404: ErrorResponseSerializer,
        500: ErrorResponseSerializer
    },
    operation_description="根据测试ID获取心理评估结果",
    operation_summary="获取评估结果"
)
@api_view(['GET'])
def get_assessment_result(request: Request, test_id: str) -> Response:
    """
    获取评估结果
    
    根据测试ID返回完整的评估结果
    """
    try:
        # 获取评估结果
        assessment_result = storage.get_assessment_result(test_id)
        
        if not assessment_result:
            return Response({
                'success': False,
                'error': 'not_found',
                'message': '评估结果不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 序列化结果
        serializer = AssessmentResultSerializer(assessment_result.to_dict())
        
        return Response(serializer.data, status=status.HTTP_200_OK)
        
    except Exception as e:
        print(f"获取评估结果时发生错误: {e}")
        return Response({
            'success': False,
            'error': 'server_error',
            'message': '服务器内部错误'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@swagger_auto_schema(
    method='get',
    manual_parameters=[
        openapi.Parameter(
            'test_id',
            openapi.IN_QUERY,
            description="测试ID",
            type=openapi.TYPE_STRING,
            required=True
        )
    ],
    responses={
        200: ShortUrlResponseSerializer,
        400: ErrorResponseSerializer,
        404: ErrorResponseSerializer,
        500: ErrorResponseSerializer
    },
    operation_description="生成或获取测试结果的短链接",
    operation_summary="获取短链接"
)
@api_view(['GET'])
def get_short_url(request: Request) -> Response:
    """
    获取短链接
    
    为指定的测试ID生成短链接
    """
    try:
        test_id = request.GET.get('test_id')
        
        if not test_id:
            return Response({
                'success': False,
                'error': 'missing_parameter',
                'message': '缺少test_id参数'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证测试ID是否存在
        assessment_result = storage.get_assessment_result(test_id)
        
        if not assessment_result:
            return Response({
                'success': False,
                'error': 'not_found',
                'message': '评估结果不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 返回短链接
        return Response({
            'short_url': assessment_result.short_url
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        print(f"获取短链接时发生错误: {e}")
        return Response({
            'success': False,
            'error': 'server_error',
            'message': '服务器内部错误'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def redirect_to_result(request: Request, test_id: str):
    """
    短链接重定向
    
    将短链接重定向到前端结果页面
    """
    try:
        # 验证测试ID是否存在
        assessment_result = storage.get_assessment_result(test_id)
        
        if not assessment_result:
            # 如果结果不存在，重定向到错误页面
            return HttpResponseRedirect(f"https://你的前端域名/error?message=结果不存在")
        
        # 重定向到前端结果页面
        frontend_url = f"https://你的前端域名/result?test_id={test_id}"
        return HttpResponseRedirect(frontend_url)
        
    except Exception as e:
        print(f"重定向时发生错误: {e}")
        return HttpResponseRedirect(f"https://你的前端域名/error?message=服务器错误")


@swagger_auto_schema(
    method='get',
    responses={
        200: openapi.Response(
            description="存储统计信息",
            schema=openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    'total_assessments': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'total_results': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'max_items': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'storage_usage_percent': openapi.Schema(type=openapi.TYPE_INTEGER),
                }
            )
        )
    },
    operation_description="获取系统存储统计信息（调试用）",
    operation_summary="存储统计"
)
@api_view(['GET'])
def storage_stats(request: Request) -> Response:
    """
    获取存储统计信息（仅用于调试和监控）
    """
    try:
        stats = storage.get_storage_stats()
        return Response(stats, status=status.HTTP_200_OK)
        
    except Exception as e:
        print(f"获取存储统计时发生错误: {e}")
        return Response({
            'error': 'server_error',
            'message': '无法获取统计信息'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@swagger_auto_schema(
    method='get',
    responses={
        200: openapi.Response(
            description="健康检查信息",
            schema=openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    'status': openapi.Schema(type=openapi.TYPE_STRING),
                    'timestamp': openapi.Schema(type=openapi.TYPE_STRING),
                    'storage_status': openapi.Schema(type=openapi.TYPE_STRING),
                    'ai_status': openapi.Schema(type=openapi.TYPE_STRING),
                }
            )
        )
    },
    operation_description="系统健康检查",
    operation_summary="健康检查"
)
@api_view(['GET'])
def health_check(request: Request) -> Response:
    """
    系统健康检查
    """
    try:
        # 检查存储状态
        storage_status = "正常"
        try:
            stats = storage.get_storage_stats()
            if stats['storage_usage_percent'] > 95:
                storage_status = "存储空间不足"
        except:
            storage_status = "存储异常"
        
        # 检查AI服务状态
        ai_status = "未配置"
        if ai_service.api_key:
            ai_status = "已配置" if ai_service.test_api_connection() else "连接失败"
        
        return Response({
            'status': '正常',
            'timestamp': datetime.now().isoformat(),
            'storage_status': storage_status,
            'ai_status': ai_status
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        print(f"健康检查时发生错误: {e}")
        return Response({
            'status': '异常',
            'timestamp': datetime.now().isoformat(),
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
